package com.kischang.blog.web.action;

import com.kischang.blog.model.TitleMenu;
import com.kischang.blog.model.Topic;
import com.kischang.blog.model.User;
import com.kischang.blog.service.TitleMenuService;
import com.kischang.blog.service.TopicService;
import com.kischang.blog.service.UserService;
import com.kischang.blog.web.actionuser.LoginAction;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.util.ValueStack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.List;


@Component
@Scope("prototype")
public class PostTopicAction extends ActionSupport implements ModelDriven<Topic>{

	private static final long serialVersionUID = 2616819579428361472L;

    private static boolean NOTPOST = true;
	@Autowired
	private TitleMenuService titleMenuService;
	@Autowired
	private TopicService topicService;
	@Autowired
	private UserService userService;
	
	private List<TitleMenu> menulist;
	private Topic topic = new Topic();
	private int mid;
	private String msg;
	private int stat;
	@Override
	public String execute() throws Exception {
        if(NOTPOST){
            stat = 3;
            msg = "系统禁用发帖！！！";
            return SUCCESS;
        }
		User user = (User) ActionContext.getContext().getSession().get(LoginAction.SESSION_USER);
		if(user == null){
			stat = 1;
			msg = "您还没有登陆！！！";
			return SUCCESS;
		}
		TitleMenu titleColumn = titleMenuService.getMenuById(mid);
		if(titleColumn == null){
			stat = 2;
			msg = "板块选择错误！！！";
			return SUCCESS;
		}
		topic.setAuthor(user);
		topic.setAuthorName(user.getNickname());
		topic.setDate(Calendar.getInstance().getTime());
		topic.setTitleColumn(titleColumn);
		topic.setState(0);
		topicService.save(topic);
		stat = 0;
		msg = "发表成功！！！";
		return SUCCESS;
	}
	
	public String view(){
		User user = (User) ActionContext.getContext().getSession().get(LoginAction.SESSION_USER);
		if(user == null){
			stat = 1;
			msg = "您还没有登陆！！！";
			return SUCCESS;
		}
		menulist = titleMenuService.getAllParentMenu();
		//
		ValueStack vs = ActionContext.getContext().getValueStack();
		vs.findValue("");
		return "view";
	}

	public List<TitleMenu> getMenulist() {
		return menulist;
	}
	public void setMid(int mid) {
		this.mid = mid;
	}
	@Override
	public Topic getModel() {
		return topic;
	}
	public String getMsg() {
		return msg;
	}
	public int getStat() {
		return stat;
	}

    public static void setNOTPOST(boolean b){
        NOTPOST = b;
    }
    public static boolean getNOTPOST(){
        return NOTPOST;
    }
}
